package week3;

public class BinarySearch<T>
{
	public static void main(String[] arguments)
	{
		BinarySearch<Integer> bs = new BinarySearch<Integer>();
		
		Integer[] ii = new Integer[] {-6, -3, 1, 7, 9};
		
		System.out.println(bs.binarySearch(ii, 7));
	}
	
	public int binarySearch(Comparable<T>[] a, T x) // zoek element x in 'a'
    {
        return binarySearch(a, 0, a.length - 1, x);
    }
    
	private static int i = 0;
	
    private int binarySearch(Comparable<T>[] a, int low, int high, T x)
    {
        System.out.println("low: " + low);
        System.out.println("high: " + high);
        System.out.println();
        
        if (low > high)
        {
        	return -1;
        }
        
    	int mid = (low + high) / 2;
        
        int c = a[mid].compareTo(x);
        
        if (c == 0)
        {
        	return mid;
        }
        
        if (c < 0)
        {
        	low = mid + 1;
        }
        else
        {
        	high = mid - 1;
        }
        
        if (i++ == 10)
        {
            return -1;
        }
        
        // Search further.
        return binarySearch(a, low, high, x);
    }
}
